<template>
  <div class="app-container">
    <el-card>
      <avue-form v-model="form" :option="option" @submit="handleSubmit">
        <template #avatar>
          <SingleImageUpload v-model="form.avatar" />
        </template>
      </avue-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { AdminModel } from "@/model/admin-model";
import adminEditOption from "./avue-option";
import AdminAPI from "@/api/system/admin";
import router from "@/router";

defineOptions({
  name: "AdminEdit",
});

const route = useRoute();
const loading = ref(false);

// 监听userId变化，重新获取数据
watch(
  () => route.query,
  async () => fetchData(),
  {
    immediate: true,
    deep: true,
  }
);

/// 表单数据
const form = ref<AdminModel>({
  // id: 0,
  // /** 姓名 */
  // name: "陈某某",
  // /** 头像 */
  // avatar: "",
  // /** 手机号 */
  // mobile: "13320098527",
  // /** 账号 */
  // username: "13320098527",
  // /** 密码 */
  // password: "123456",
  // /** 角色ID */
  // auth_group_id: undefined,
  // /** 状态 */
  // status: 1,
});
const option = ref<Object>(adminEditOption);

/**
 * @description 获取数据
 */
function fetchData() {
  const userId = route.query.id;
  loading.value = true;
  AdminAPI.detail(Number(userId))
    .then((res) => {
      form.value = res;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * @description 表单提交
 * @param form 表单数据
 * @param done 完成函数
 */
const handleSubmit = (form: Object, done: Function) => {
  AdminAPI.edit(form)
    .then(() => {
      ElMessage.success("操作成功");
      router.back();
    })
    .finally(() => {
      done();
    });
};
</script>
